package org.scache.serialization.hessian;


import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import org.scache.log.InternalLogger;
import org.scache.serialization.ISerializer;
import org.scache.serialization.hessian.io.IOPutLocalCache;
import org.scache.serialization.hessian.io.ReusableByteArrayInputStream;
import org.scache.serialization.hessian.io.ReusableByteArrayOutputStream;

import java.io.IOException;
import java.io.Serializable;

/**
 * Hessian2 序列化
 *
 * @author 君枫
 * @since 2014年3月12日 上午11:02:31
 */
public class Hessian2Serializer implements ISerializer {

    @Override
    public byte[] serialize(Serializable s) {
        if (s != null) {
            ReusableByteArrayOutputStream bos = IOPutLocalCache.LOCAL_OUTPUT_STREAM.get();
            bos.init();
            Hessian2Output ho = IOPutLocalCache.LOCAL_HESSIAN2_OUTPUT.get();
            ho.init(bos);
            try {
                ho.writeObject(s);
                ho.flush();
                return bos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
                InternalLogger.error("序列化对象失败:" + e.getMessage());
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T deserialize(byte[] bytes) {
        if (bytes != null) {
            ReusableByteArrayInputStream bis = IOPutLocalCache.LOCAL_INPUT_STREAM.get();
            bis.init(bytes);
            Hessian2Input hi = IOPutLocalCache.LOCAL_HESSIAN2_INPUT.get();
            hi.init(bis);
            try {
                return (T) hi.readObject();
            } catch (IOException e) {
                e.printStackTrace();
                InternalLogger.error("反序列化对象失败:" + e.getMessage());
            }
        }
        return null;
    }


}
